<template>
  <!-- 会员等级添加/修改 -->
  <el-dialog
    v-model="visible"
    :close-on-click-modal="false"
    :title="$t('user.levelConfig')"
  >
    <el-tabs
      v-model="activeName"
      type="card"
    >
      <el-tab-pane
        :label="$t('user.generalConfiguration')"
        name="first"
      >
        <div class="prods-select-body">
          <!-- native modifier has been removed, please confirm whether the function has been affected  -->
          <el-form
            ref="dataFormRef"
            :model="dataForm"
            :label-width="$t('language')==='English'?'170px':'150px'"
            :rules="dataRule"
            @submit.prevent
          >
            <el-form-item
              :label="$t('user.levelNameCn')"
              prop="levelNameCn"
            >
              <el-input
                v-model="dataForm.levelNameCn"
                :placeholder="$t('user.enterGradeNameCn')"
                maxlength="10"
                style="width: 400px"
                show-word-limit
              />
            </el-form-item>
            <el-form-item
              :label="$t('user.levelNameEn')"
              prop="levelNameEn"
            >
              <el-input
                v-model="dataForm.levelNameEn"
                :placeholder="$t('user.enterGradeNameEn')"
                maxlength="10"
                style="width: 400px"
                show-word-limit
              />
            </el-form-item>
            <el-form-item
              :label="$t('user.levelStyle')"
              prop="levelStyle"
            >
              <el-radio-group v-model="dataForm.levelStyle">
                <el-radio :label="0">
                  {{ $t("user.custom") }}
                </el-radio>
                <el-radio
                  v-if="dataForm.levelType !==1"
                  :label="1"
                >
                  {{ $t("user.bronze") }}
                </el-radio>
                <el-radio
                  v-if="dataForm.levelType === 1"
                  :label="2"
                >
                  {{ $t("user.silver") }}
                </el-radio>
                <el-radio
                  v-if="dataForm.levelType === 1"
                  :label="3"
                >
                  {{ $t("user.gold") }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              v-if="!dataForm.levelStyle"
              :label="$t('user.bgImg')"
              prop="img"
            >
              <img-upload v-model="dataForm.img" />
              <div
                class="el-form-item-tips"
                style="width: 100%;"
              >
                {{ $t("user.imgsTip") + '150*70' + $t("user.px") }}
              </div>
            </el-form-item>
            <el-form-item
              v-if="dataForm.levelType === 1"
              :label="$t('user.paidMemberPrice')"
              prop="needAmount"
            >
              <el-input
                v-model.number="dataForm.needAmount"
                :placeholder="$t('user.enterPrice')"
                min="0.01"
                style="width: 400px"
                oninput="if(value.length>10)value=value.slice(0,10)"
                step="0.0000001"
                @change="dataForm.needAmount = oninput(dataForm.needAmount)"
              >
                <template #append>
                  {{ $t("coupon.yuan") }}
                </template>
              </el-input>
            </el-form-item>
            <el-form-item
              v-if="dataForm.levelType === 1"
              :label="$t('user.timeType')"
              prop="termType"
            >
              <el-radio-group v-model="dataForm.termType">
                <el-radio :label="1">
                  {{ $t("user.day") }}
                </el-radio>
                <el-radio :label="2">
                  {{ $t("user.week") }}
                </el-radio>
                <el-radio :label="3">
                  {{ $t("user.month") }}
                </el-radio>
                <el-radio :label="4">
                  {{ $t("user.season") }}
                </el-radio>
                <el-radio :label="5">
                  {{ $t("user.year") }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              v-if="dataForm.levelType === 1"
              :label="$t('user.time')"
              prop="term"
            >
              <el-input
                v-model.number="dataForm.term"
                :placeholder="$t('user.enterInteger')"
                min="1"
                precision="0"
                style="width: 400px"
                oninput="if(value.length>5)value=value.slice(0,5)"
                @change="dataForm.term = termOnInput(dataForm.term, dataForm.termType)"
              >
                <template #append>
                  {{
                    dataForm.termType === 1
                      ? $t("user.day")
                      : dataForm.termType === 2
                        ? $t("user.week")
                        : dataForm.termType === 3
                          ? $t("user.month")
                          : dataForm.termType === 4
                            ? $t("user.season")
                            : $t("user.year")
                  }}
                </template>
              </el-input>
              <el-tooltip
                class="item"
                effect="dark"
                :content="$t('user.maxTimeTip')"
                placement="top"
              >
                <el-icon><InfoFilled /></el-icon>
              </el-tooltip>
            </el-form-item>
            <el-form-item
              :label="$t('user.requiredGrowthValue')"
              prop="needGrowth"
            >
              <el-input
                v-model.number="dataForm.needGrowth"
                :placeholder="$t('user.enterInteger')"
                style="width: 400px"
                :min="minNeedGrowth"
                :max="maxNeedGrowth"
                precision="0"
                :disabled="dataForm.level === 1 && dataForm.levelType === 0"
              >
                <template #append>
                  {{ $t("user.growth") }}
                </template>
              </el-input>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <el-tab-pane
        :label="$t('user.equityAllocation')"
        name="third"
      >
        <div class="prods-select-body">
          <!-- native modifier has been removed, please confirm whether the function has been affected  -->
          <el-form
            label-width="30px"
            @submit.prevent
          >
            <el-form-item prop="isFreeFee">
              <el-checkbox v-model="isFreeFee">
                {{
                  lang === 'zh_CN' ? sysRightName.freeShipping[0]?.rightsName : sysRightName.freeShipping[1]?.rightsName
                }}
              </el-checkbox>
            </el-form-item>
            <el-form-item prop="couponList">
              <el-checkbox v-model="isCoupon">
                {{
                  lang === 'zh_CN' ? sysRightName.sendCoupon[0]?.rightsName : sysRightName.sendCoupon[1]?.rightsName
                }}
              </el-checkbox>
              <template v-if="isCoupon">
                <span style="margin: 0 20px">
                  <!-- native modifier has been removed, please confirm whether the function has been affected  -->
                  <el-button
                    link
                    type="primary"
                    @click="conpouSelectHandle()"
                  >{{ $t("user.selectCoupons") }}</el-button>
                </span>
                <span
                  v-for="(item, index) in dataForm.couponList"
                  :key="index"
                >
                  <span v-if="index < 2">{{ item.couponName
                  }}{{
                    index == 1 && dataForm.couponList.length > 2
                      ? $t("user.etcCoupons")
                      : ""
                  }}</span>
                  &nbsp;
                </span>
              </template>
            </el-form-item>
            <el-form-item prop="discount">
              <el-checkbox v-model="isDiscount">
                {{
                  lang === 'zh_CN' ? sysRightName.discount[0]?.rightsName : sysRightName.discount[1]?.rightsName
                }}
              </el-checkbox>
              <el-input-number
                v-if="isDiscount"
                v-model="dataForm.discount"
                :placeholder="$t('user.discountRange')"
                :min="0.01"
                :max="10"
                :precision="2"
                controls-position="right"
                style="width: 160px;margin-left:4px;"
              >
                <template #append>
                  {{ $t("marketing.fold") }}
                </template>
              </el-input-number>
              <div
                style="color:red;"
                class="disabled-btn text-btn default-btn"
              >
                {{ $t("marketing.discountTip1") }}
              </div>
            </el-form-item>
            <el-form-item
              prop="discountType"
              class="discount-body"
            >
              <el-radio-group
                v-if="isDiscount"
                v-model="dataForm.discountType"
              >
                <el-radio :label="0">
                  {{ $t("user.allProducts") }}
                </el-radio>
                <el-radio :label="1">
                  {{ $t("user.categoryGoods") }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              v-if="isDiscount && dataForm.discountType === 1"
              prop="categorys"
            >
              <el-tree
                ref="categoryTreeRef"
                :data="categoryList"
                :props="categoryListTreeProps"
                node-key="categoryId"
                show-checkbox
              />
            </el-form-item>
            <el-form-item prop="discountRange">
              <el-checkbox v-model="isOrther">
                {{
                  $t("user.otherRights")
                }}
              </el-checkbox>
              <el-checkbox-group
                v-if="isOrther"
                v-model="userRightsIds"
                @change="checkbox"
              >
                <el-checkbox
                  v-for="item in rightsDataList"
                  :key="item.rightsId"
                  style="margin:4px 30px 0 0"
                  :label="item.rightsId"
                  border
                >
                  {{ item.rightsName }}
                </el-checkbox>
              </el-checkbox-group>
              <div
                style="color:red;"
                class="disabled-btn text-btn default-btn"
              >
                {{ $t("marketing.discountTip2") }}
              </div>
            </el-form-item>
          </el-form>
          <coupon-select
            ref="couponSelectRef"
            data-url="/admin/coupon/listCanSendCoupon"
            :get-way="1"
            @refresh-select-coupon-list="selectDistributionCoupon"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <div>
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("user.cancel") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="submitProds()"
        >
          {{ $t("user.confirm") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])

const dataForm = ref({
  id: null,
  level: 0,
  levelNameCn: '',
  levelNameEn: '',
  levelType: 0,
  levelStyle: 0,
  needGrowth: 0,
  needAmount: 0,
  term: 1,
  termType: 1,
  img: '',
  discount: 10,
  discountRange: 0,
  discountType: 0,
  isFreeFee: 0,
  couponList: [],
  userRightsIds: [],
  categoryList: [],
  categorys: []
})
let maxNeedGrowth = null
const categoryListTreeProps = reactive({
  label: 'name',
  children: 'children'
})
const sysRightName = reactive({
  freeShipping: [],
  sendCoupon: [],
  discount: []
})
const lang = localStorage.getItem('bbcLang') || 'zh_CN'

// eslint-disable-next-line no-unused-vars
const validateTime = (rule, value, callback) => {
  const reg = /^[1-9]\d*$/
  if (!reg.test(dataForm.value.term)) {
    callback(new Error($t('user.integerGreaterThanZero')))
  } else {
    callback()
  }
}

const minNeedGrowth = ref(null)
// eslint-disable-next-line no-unused-vars
const validateNeedGrowth = (rule, value, callback) => {
  const num = setNumber(dataForm.value.needGrowth)
  if (maxNeedGrowth) {
    if (num > maxNeedGrowth) {
      callback(new Error($t('user.requiredGrowthValueMaximum')))
    }
  }
  if (num < minNeedGrowth.value) {
    callback(new Error($t('user.requiredGrowthValueMinimum')))
  } else {
    callback()
  }
}
const dataRule = {
  levelNameCn: [
    { required: true, message: $t('user.gradeNmaeCannotEmptyCn'), trigger: 'blur' }
  ],
  img: [
    { required: true, message: $t('user.bgImgCannotEmpty'), trigger: 'blur' }
  ],
  term: [
    { required: true, validator: validateTime, trigger: 'blur' }
  ],
  needGrowth: [
    { required: true, validator: validateNeedGrowth, trigger: 'blur' }
  ],
  levelStyle: [
    { required: true, message: $t('user.enterLevelStyle'), trigger: 'change' }
  ]
}

onActivated(() => {
  getDataList()
})

const visible = ref(false)
const activeName = ref('first')
const isFreeFee = ref(false)
const isCoupon = ref(false)
const isDiscount = ref(false)
const isOrther = ref(false)
let isSubmit = false
const userRightsIds = ref([])

// 获取数据列表
const init = (userLevels, index) => {
  // 初始化
  visible.value = true
  activeName.value = 'first'
  isFreeFee.value = false
  isCoupon.value = false
  isDiscount.value = false
  isOrther.value = false
  isSubmit = true
  if (userLevels[index].id) {
    getDataList(userLevels, index)
  } else {
    // 保存直接写入数据
    dataForm.value = userLevels[index]
    dataForm.value.couponList = dataForm.value.couponList || []
    userRightsIds.value = dataForm.value.userRightsIds
    // 设置所需积分最大最小值
    serMinOrMaxNeedGrowth(userLevels, index)
    getCategoryDataList()
    getRightsDataList()
  }
  // 获取系统权益名称
  getSysRightList()
  nextTick(() => {
    dataFormRef.value.clearValidate()
  })
}

/**
 * 获取初始话数据
 */
const getDataList = (userLevels, index) => {
  http({
    url: http.adornUrl('/user/userLevel/info/' + parseInt(userLevels[index].id)),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data?.userLevelLangList) {
      data.userLevelLangList.forEach(val => {
        const levelName = ['levelNameCn', 'levelNameEn'][val.lang]
        data[levelName] = val.levelName
      })
    }
    dataForm.value = data
    userRightsIds.value = data.userRightsIds
    setRightsStatus(data)
    serMinOrMaxNeedGrowth(userLevels, index)
    getCategoryDataList()
    getRightsDataList()
  })
}

const categoryList = ref([])
const categoryTreeRef = ref(null)
/**
 * 获取商品分类列表
 */
const getCategoryDataList = () => {
  http({
    url: http.adornUrl('/prod/category/listSigningCategory'),
    method: 'get',
    params: http.adornParams({ status: 1 })
  }).then(({ data }) => {
    categoryList.value = data
    if (dataForm.value.discountType === 1) {
      categoryTreeRef.value?.setCheckedKeys(dataForm.value.categorys)
    }
  })
}

const rightsDataList = ref([])

/**
 * 获取系统权益
 */
const getSysRightList = () => {
  http({
    url: http.adornUrl('/user/userRights/page'),
    method: 'get',
    params: {
      serviceType: 0
    }
  }).then(({ data }) => {
    const sysRights = data.records
    for (let i = 0; i < sysRights.length; i++) {
      // 包邮
      if (i === 0) {
        sysRightName.freeShipping = sysRights[i].userRightsLangList
      }
      // 打折
      if (i === 1) {
        sysRightName.discount = sysRights[i].userRightsLangList
      }
      // 送优惠券
      if (i === 2) {
        sysRightName.sendCoupon = sysRights[i].userRightsLangList
      }
    }
  })
}

/**
 * 获取用户权益列表
 */
const getRightsDataList = () => {
  http({
    url: http.adornUrl('/user/userRights/list'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    const lang = localStorage.getItem('bbcLang') || 'zh_CN'
    data.forEach(element => {
      let rightsNameCn, rightsNameEn
      if (!element.userRightsLangList) return
      element.userRightsLangList.forEach(val => {
        if (val.lang === 0) rightsNameCn = val.rightsName
        if (val.lang === 1) rightsNameEn = val.rightsName
      })
      element.rightsName = lang === 'zh_CN' ? rightsNameCn : rightsNameEn || rightsNameCn
    })
    rightsDataList.value = data
  })
}

/**
 * 设置所需积分最大最小值
 */
const serMinOrMaxNeedGrowth = (userLevels, index) => {
  if (userLevels[index].level > 1) {
    minNeedGrowth.value = userLevels[index - 1].needGrowth === 1000000000 ? userLevels[index - 1].needGrowth : userLevels[index - 1].needGrowth + 1
  } else {
    minNeedGrowth.value = 0
  }
  if (index < userLevels.length - 1 && userLevels[index + 1].needGrowth !== 0) {
    maxNeedGrowth = userLevels[index + 1].needGrowth - 1
  } else {
    maxNeedGrowth = 1000000000
  }
}

const couponSelectRef = ref(null)
/**
 * 显示添加指定优惠券弹框
 */
const conpouSelectHandle = () => {
  nextTick(() => {
    couponSelectRef.value?.init(dataForm.value.couponList)
  })
}

/**
 * 优惠券选择回调
 */
const selectDistributionCoupon = (coupons) => {
  if (coupons.length > 0) {
    dataForm.value.couponList = coupons
    dataForm.value.couponList = coupons
  } else {
    dataForm.value.couponList = []
    isCoupon.value = false
  }
}

/**
 * 权益选项数据校验
 */
const setRights = () => {
  // 邮费
  if (isFreeFee.value) {
    dataForm.value.isFreeFee = 1
  } else {
    dataForm.value.isFreeFee = 0
  }
  // 折扣
  if (!isDiscount.value) {
    dataForm.value.discount = 10
    dataForm.value.discountRange = 0
    dataForm.value.discountType = 0
  }
  // 优惠券
  if (!isCoupon.value) {
    dataForm.value.couponList = []
  }
  // 其他权益
  if (!isOrther.value) {
    dataForm.value.userRightsIds = []
  } else {
    dataForm.value.userRightsIds = userRightsIds.value
  }
}

let msg = ''
let isCheckSccuss = null
const checkData = () => {
  if (!dataForm.value.img && !dataForm.value.levelStyle) {
    msg = $t('user.bgImgCannotEmpty')
    isCheckSccuss = false
    return false
  }
  if (!dataForm.value.levelNameCn || dataForm.value.levelNameCn.length < 1 || !dataForm.value.levelNameCn.trim()) {
    msg = $t('user.gradeNmaeCannotEmptyCn')
    isCheckSccuss = false
    return false
  }
  if (isDiscount.value) {
    if (dataForm.value.discountType === 1 && categoryTreeRef.value?.getCheckedKeys().length === 0) {
      msg = $t('user.selectCategory')
      isCheckSccuss = false
      return false
    }
  }
  // 优惠券
  if (isCoupon.value && dataForm.value.couponList.length < 1) {
    msg = $t('user.selectCoupons')
    isCheckSccuss = false
    return false
  }
  // 折扣
  if (isDiscount.value) {
    if (!dataForm.value.discount) {
      msg = $t('user.discountRange')
      isCheckSccuss = false
      return false
    } else if (dataForm.value.discount === 10) {
      msg = $t('user.discountRangeValue')
      isCheckSccuss = false
      return false
    }
  }
}

const dataFormRef = ref(null)
/**
 * 确定事件
 */
const submitProds = () => {
  if (!isSubmit) {
    return
  }
  // 校验数据
  isCheckSccuss = true
  checkData()
  if (!isCheckSccuss) {
    errorMsg(msg)
    return
  }
  // 数据校验
  dataFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    isSubmit = false
    // 根据数据设置权限
    setRights()
    if (dataForm.value.discountType === 1) {
      dataForm.value.categorys = categoryTreeRef.value?.getCheckedKeys()
    }
    if (!isDiscount.value || !dataForm.value.discountType) {
      dataForm.value.categorys = null
    }
    dataForm.value.levelName = dataForm.value.levelNameCn
    if (dataForm.value.userLevelLangList) {
      dataForm.value.userLevelLangList.forEach((val) => {
        if (val.lang === 0) val.levelName = dataForm.value.levelNameCn
        if (val.lang === 1) val.levelName = dataForm.value.levelNameEn
      })
    } else {
      dataForm.value.userLevelLangList = [
        {
          lang: 0,
          levelName: dataForm.value.levelNameCn
        },
        {
          lang: 1,
          levelName: dataForm.value.levelNameEn
        }
      ]
    }
    if (dataForm.value.levelStyle !== 0) {
      dataForm.value.img = null
      dataForm.value.rightImg = null
    }
    http({
      url: http.adornUrl('/user/userLevel'),
      method: dataForm.value.id ? 'put' : 'post',
      data: http.adornData(dataForm.value)
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500
      })
      emit('refreshDataList')
    }).catch(() => { })
    dataForm.value = {}
    visible.value = false
  })
}

const setRightsStatus = (data) => {
  data.isFreeFee === 0 ? isFreeFee.value = false : isFreeFee.value = true
  data.discount === 10 ? isDiscount.value = false : isDiscount.value = true
  data.couponList.length < 1 ? isCoupon.value = false : isCoupon.value = true
  data.userRightsIds.length < 1 ? isOrther.value = false : isOrther.value = true
}

const oninput = (needAmount) => {
  let amount = parseFloat(needAmount)
  if (isNaN(amount)) {
    return 0.01
  }
  amount = +Number(needAmount).toFixed(2)
  if (amount === 0) {
    amount = 0.01
  }
  let cur = amount.toString()
  let reString = cur.indexOf('.')
  if (reString < 0) {
    reString = cur.length
    cur += '.'
  }
  while (cur.length <= reString + 2) {
    cur += '0'
  }
  if (parseFloat(needAmount) < 0) {
    return 0.01
  }
  return parseFloat(cur).toFixed(2)
}

/**
 * 时间校验，最大10年
 */
const termOnInput = (term, termType) => {
  if (isNaN(term)) {
    return 1
  }
  switch (termType) {
    case 1: term = Math.min(3652, term)
      break
    case 2: term = Math.min(522, term)
      break
    case 3: term = Math.min(120, term)
      break
    case 4: term = Math.min(40, term)
      break
    case 5: term = Math.min(10, term)
      break
    default:
      break
  }
  return term
}

/**
 * 权益多选时触发事件
 */
const checkbox = () => {}

/**
 * 判断数据
 */
const setNumber = (value) => {
  const num = Math.round(value)
  if (num < 0) {
    return 0
  } else {
    return num
  }
}

/**
 * 错误提示框
 */
const errorMsg = (message) => {
  ElMessage({
    message,
    type: 'error',
    duration: 1500
  })
}

defineExpose({
  init
})

</script>

<style lang="scss" scoped>
.prods-select-body {
  height: 500px;
  overflow: auto;
}
.discount-body {
  margin-left: 30px;
  overflow: auto;
}
</style>
